﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;

namespace BitPortal.Handlers
{
    /// <summary>
    /// Lấy thumb ảnh theo kích thước truyền vào, có lưu vào cache!
    /// </summary>
    public class Thumbnail : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string photoFile = context.Request.QueryString["p"];
            context.Response.ContentType = "image/jpeg";
            //Search form cache
            //Get key
            string hashCode = GetKey();
            //Key Exist
            if (context.Cache[hashCode] != null)
            {
                (context.Cache[hashCode] as Bitmap).Save(context.Response.OutputStream, ImageFormat.Jpeg);
                return;
            }
            //Get path
            string photoPath = context.Server.MapPath("~" + photoFile);
            Bitmap photo;
            try
            {
                photo = new Bitmap(photoPath);
            }
            catch (ArgumentException)
            {
                throw new HttpException(404, "Photo not found.");
            }
            //Get size
            int width, height;
            width = Utils.GeneralUtils.ToInt32TryParse(context.Request.QueryString["w"]);
            height = Utils.GeneralUtils.ToInt32TryParse(context.Request.QueryString["h"]);
            if (context.Request.QueryString["relative"] == "1")
            {
                width = photo.Width * width / 100;
                height = photo.Height * height / 100;
            }
            if (width > 0 && height == 0)
            {
                height = photo.Height * width / photo.Width;
            }
            else if (width == 0 && height > 0)
            {
                width = photo.Width * height / photo.Height;
            }
            else if (width == 0 && height == 0)
            {
                width = 120;
                height = 100;
            }
            Bitmap target = new Bitmap(width, height);
            using (Graphics graphics = Graphics.FromImage(target))
            {
                graphics.CompositingQuality = CompositingQuality.HighSpeed;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.DrawImage(photo, 0, 0, width, height);
                //photo.Dispose();

                context.Cache.Insert(hashCode, target, null, DateTime.Now.AddYears(1), TimeSpan.Zero);
                target.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                //target.Dispose();

            }
        }

        private static string GetKey(string p, string h, string w)
        {
            return (p + h + w).GetHashCode().ToString();

        }
        private static string GetKey()
        {
            return HttpContext.Current.Request.Url.Query.GetHashCode().ToString();
        }

        private static void OutputCacheResponse(HttpContext context, DateTime lastModified)
        {
            HttpCachePolicy cachePolicy = context.Response.Cache;
            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.VaryByParams["p"] = true;
            cachePolicy.SetOmitVaryStar(true);
            cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365));
            cachePolicy.SetValidUntilExpires(true);
            cachePolicy.SetLastModified(lastModified);
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}